import * as mammoth from "mammoth";
import htmlDocx from 'html-docx-js/dist/html-docx'
import AbstractCat2DocFile from "./file";
import saveAs from 'file-saver'
/** Docx文件 */
class DocxFile extends AbstractCat2DocFile {
    /** 获取文件扩展名 */
    getExtension(){
        return 'DOCX';
    }
    /** 导出文件 */
    export(fileName, element) {
        return new Promise((resolve,reject)=> {
            try {
                const converted = htmlDocx.asBlob(`
      <html xmlns:o=\'urn:schemas-microsoft-com:office:office\' xmlns:w=\'urn:schemas-microsoft-com:office:word\' xmlns=\'http://www.w3.org/TR/REC-html40\'><head>
      ${document.head.outerHTML}
      </head><body>${element.outerHTML}</body></html>`);
                saveAs(converted, fileName);
                resolve({});
            }catch (err) {
                reject(err)
            }
        });
    }
    /** 导入文件 */
    import(file) {
        return new Promise((resolve,reject)=>{
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    mammoth.convertToHtml({arrayBuffer: e.target.result}, {
                        // convertImage: mammoth.images.imgElement(function(image) {
                        //   return image.read("base64").then(function (imageBuffer) {
                        //     // const formData = new FormData();
                        //     // formData.append('file', imageBuffer);
                        //     // let res = up load(formData);
                        //     // console.log('res',res);
                        //     const id = 'cache_'+new Date().getTime()+'_'+Math.trunc(Math.random() * 1000000000)+'_img'
                        //     // LocalForage.setItem(id, "data:" + image.contentType + ";base64," + imageBuffer);
                        //     cacheFiles.set(id, "data:" + image.contentType + ";base64," + imageBuffer);
                        //     return {
                        //       src: "",
                        //       cacheId: id
                        //     };
                        //   });
                        // })
                    }).then(r=>{
                        if(r.messages && r.messages.length>0) {
                            // console.warn('docx文档解析告警', r)
                        }
                        resolve(r.value);
                    }).catch(err=>{
                        reject(err)
                    })
                };
                reader.readAsArrayBuffer(file);
            }
        });
    }
}

export default DocxFile;
